package com.ocean.common.utils.file;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.*;


/**
* Title: PptToHtml
* Description:  ppt转html
* @author dingxy
* @date 2018年12月3日
*/
public class PptToHtmlUtils{

    /**
     * Title: pptToPicture
     * Description:
     * @param tempContextUrl 原ppt路径
     * @param outPath  转化后输出路径
     * @param fileName  原文件名称
     */
    public static String pptToPicture(String tempContextUrl,String outPath,String fileName){
    	File parentfolder = new File(outPath);
        if (!parentfolder.exists()) { //判断是否存在
        	parentfolder.mkdirs();
    	}

    	String prefixFileName=fileName.substring(0,fileName.lastIndexOf(".")); //获取前缀名

    	//文件夹名
        List<String> imgList = new ArrayList<String>();
        File file = new File(tempContextUrl);
        File folder = new File(outPath + File.separator + prefixFileName);
        if (!folder.exists()) { //判断是否存在
        	folder.mkdirs();
    	}
        try {
            FileInputStream is = new FileInputStream(file);
            SlideShow ppt = new SlideShow(is);
            is.close();
            Dimension pgsize = ppt.getPageSize();
            org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                TextRun[] truns = slide[i].getTextRuns();
                for ( int k=0;k<truns.length;k++){
                    RichTextRun[] rtruns = truns[k].getRichTextRuns();
                    for(int l=0;l<rtruns.length;l++){
                        rtruns[l].setFontIndex(1);
                        rtruns[l].setFontName("宋体");
                    }
                }
                BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.BLUE);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                String imgName = File.separator + prefixFileName + File.separator +"pict_"+ (i + 1) + ".jpeg";
                FileOutputStream out = new FileOutputStream(outPath + imgName);
                javax.imageio.ImageIO.write(img, "jpeg", out);
                out.close();
                //imgList.add(prefixFileName + File.separator +"pict_"+ (i + 1) + ".jpeg");
                imgList.add("pict_"+ (i + 1) + ".jpeg");
            }
        } catch (FileNotFoundException e) {
        	// 如果没有找到文件，把上面生成的文件夹删掉
        	deleteFile(new File(outPath + File.separator + prefixFileName));
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        //createPPTHtml(outPath,imgList, tempContextUrl,fileName);
        String filePath = createPPTHtml(outPath + File.separator + prefixFileName,imgList, tempContextUrl,prefixFileName);
        try { // 保证上面的文件流能操作完
			Thread.sleep(15000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return filePath;
    }

    /**自己创建的html代码
     * 原理上就是，把上一步ppt转的图片
     * 以html的方式呈现出来
     */
    private static String createPPTHtml(String wordPath,List<String> imgList,String tempContextUrl,String fileName){
    	String endPath =""; // 最终返回路径
    	String endPathTemp =""; // 临时路径
        StringBuilder sb = new StringBuilder("<!doctype html><html><head><meta charset='utf-8'><title>在线预览</title></head><body><div align=\"center\">");
        if (imgList != null && !imgList.isEmpty()) {
            for (String img : imgList) {
                sb.append("<img width='950px;' src='" + img + "' /><br>");
            }
        }
        sb.append("</div></body></html>");
        try {
        	endPathTemp = wordPath + File.separator +fileName+".html";
            File file = new File(endPathTemp);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
            bufferedWriter.write(sb.toString());
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String attrstemp =endPathTemp.replace("\\", ",").replace("/",",").replace("//",",");
        String[] attrs = attrstemp.split(",");
        // 对路径进行截取
        //String[] attrs =endPathTemp.split("\\\\");
        String name0 = attrs[attrs.length-4];
        String name1 = attrs[attrs.length-3];
		String name2 = attrs[attrs.length-2];
		String name3 = attrs[attrs.length-1];
		endPath = name0+File.separator+name1+File.separator+name2+File.separator+name3;
		return endPath;
    }

    private static boolean deleteFile(File dirFile) {
    	System.out.println("--------删除------------");
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {
            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }
        return dirFile.delete();
    }

    /**
     * Title: deleteFile
     * Description:   删除单个文件
     * @param fileName
     * @return
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * Title: deleteDirectory
     * Description:  删除目录及目录下的文件
     * @param dir
     * @return
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }


    /**
     * Title: pptTohtml07
     * Description:  pptx 转换为html
     * @param filepath 原pptx路径
     * @param outPath  转化后输出路径
     * @param fileName  原文件名称
     * @throws IOException
     * @throws TransformerException
     */
    public static String pptTohtml07(String filepath,String outPath,String filename){

    	File parentfolder = new File(outPath);
        if (!parentfolder.exists()) { //判断是否存在
        	parentfolder.mkdirs();
    	}

    	String prefixFileName = filename.substring(0,filename.lastIndexOf(".")); //获取前缀名
    	File filefolder = new File(outPath+File.separator+prefixFileName+File.separator);
        if (!filefolder.exists()) { //判断是否存在
        	filefolder.mkdirs();
    	}

	    String htmlname = prefixFileName+".html";
		File file = new File(filepath);
		boolean isppt = checkFile(file);
        if (!isppt) {
            System.out.println("The image you specify don't exit!");
            deleteFile(new File(outPath + File.separator + prefixFileName));
            return "";
        }
		FileInputStream is = null;
		XMLSlideShow pptx = null;

		try {
			is = new FileInputStream(file);
			pptx = new XMLSlideShow(is);
			is.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	     Dimension pgsize = pptx.getPageSize();
	     List<XSLFSlide> pptPageXSLFSLiseList = pptx.getSlides();
         FileOutputStream out = null;
         StringBuilder imghtml = new StringBuilder("");
         for (int i = 0; i < pptPageXSLFSLiseList.size(); i++) {
             try {
                 for(XSLFShape shape : pptPageXSLFSLiseList.get(i).getShapes()){
                     if(shape instanceof XSLFTextShape) {
                         XSLFTextShape tsh = (XSLFTextShape)shape;
                         for(XSLFTextParagraph p : tsh){
                             for(XSLFTextRun r : p){
                                 r.setFontFamily("宋体");
                             }
                         }
                     }
                 }
                 BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                 Graphics2D graphics = img.createGraphics();
                 // clear the drawing area
                 graphics.setPaint(Color.blue);
                 graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

                 // render
                 pptPageXSLFSLiseList.get(i).draw(graphics);

                 String imgName = File.separator + prefixFileName + File.separator +"pict_"+ (i + 1) + ".jpg";

                 out = new FileOutputStream(outPath + imgName);
                 javax.imageio.ImageIO.write(img, "jpg", out);

                 //图片在html加载路径
                 String imgs = "pict_"+(i + 1) + ".jpg";
	             imghtml.append("<img src=\'"+imgs+"\' style=\'width:1000px;height:800px;vertical-align:text-bottom;\'><br><br><br><br>");
             } catch (Exception e) {
            	 System.out.println(e);
                 System.out.println("第"+i+"张pptx转换出错");
             }
         }

         try {
			Thread.sleep(15000);
		 } catch (InterruptedException e1) {
			e1.printStackTrace();
		 }

         DOMSource domSource = new DOMSource();
 		 StreamResult streamResult = new StreamResult(out);
 		 TransformerFactory tf = TransformerFactory.newInstance();
 		 Transformer serializer;
		 try {
			serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
	 		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
	 		serializer.setOutputProperty(OutputKeys.METHOD, "html");
	 		serializer.transform(domSource, streamResult);
		 } catch (TransformerConfigurationException e) {
			e.printStackTrace();
			return "";
		 }catch (TransformerException e) {
			e.printStackTrace();
			return "";
		 }

         try {
			out.close();
		 } catch (IOException e) {
			e.printStackTrace();
		 }

         String ppthtml="<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>"+imghtml.toString()+"</body></html>";
         //FileUtils.writeStringToFile(new File(filepath, htmlname), ppthtml, "utf-8");
         try {
        	try {
 				Thread.sleep(5000);
 			} catch (InterruptedException e1) {
 				e1.printStackTrace();
 			}
        	//FileUtils.writeStringToFile(new File(filepath, htmlname), ppthtml, "utf-8");
			FileUtils.writeStringToFile(new File(outPath+File.separator+prefixFileName+File.separator, htmlname), ppthtml, "utf-8");
			String endPathTemp = outPath+File.separator+prefixFileName+File.separator+ htmlname;

	        String attrstemp =endPathTemp.replace("\\", ",").replace("/",",").replace("//",",");
	        String[] attrs = attrstemp.split(",");
	        // 对路径进行截取
	        //String[] attrs =endPathTemp.split("\\\\");
	        String name0 = attrs[attrs.length-4];
	        String name1 = attrs[attrs.length-3];
			String name2 = attrs[attrs.length-2];
			String name3 = attrs[attrs.length-1];
			String endPath = name0+File.separator+name1+File.separator+name2+File.separator+name3;
			System.out.println(endPath);
			return endPath;
         } catch (IOException e) {
			deleteFile(new File(outPath + File.separator + prefixFileName + File.separator));
			//deleteDirectory(outPath + File.separator + prefixFileName + File.separator);
			e.printStackTrace();
			return "";
		 }
    }

    // function 检查文件是否为PPT
    public static boolean checkFile(File file) {
        boolean isppt = false;
        String filename = file.getName();
        String suffixname = null;
        if (filename != null && filename.indexOf(".") != -1) {
            suffixname = filename.substring(filename.indexOf("."));
            if (suffixname.equals(".ppt")||suffixname.equals(".pptx")) {
                isppt = true;
            }
            return isppt;
        } else {
            return isppt;
        }
    }


    public static void main(String[] args) throws IOException {
        /*pptToPicture("D:\\cloud\\ocean\\NMF\\PPT\\emergency\\0001111.pptx",
        		"D:\\cloud\\ocean\\NMF\\PPTPPT\\PPTPREVIEW\\","0001111.pptx");*/

        pptTohtml07("D:\\cloud\\ocean\\NMF\\PPT\\emergency\\0001111.pptx","D:\\cloud\\ocean\\NMF\\PPT\\emergency", "0001111.pptx");
    }

}
